﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace AutoPageHelper
{
    public class ActionParser
    {
        protected static int urlIndex;
        protected static List<string> urls = new List<string>();
        protected string action;
        protected string paramId;
        protected string paramVal;
        public string ParseAction(string actionText)
        {
            string strText = PreProcess(actionText);
            if (string.IsNullOrEmpty(action))
                return strText;
            strText = Parse();
            strText = ParseIndex(strText);
            return strText;
        }
        protected virtual string Parse()
        {
            return string.Format("// {0}:{{{1}:{2}}}", action, paramId, paramVal);
        }
        private string ParseIndex(string param)
        {
            param = param.Replace("{pageIndex}", urlIndex.ToString());
            param = param.Replace("{mapIndex}", urlIndex.ToString());
            param = param.Replace("{dataIndex}", urlIndex.ToString());
            return param;
        }

        protected string PreProcess(string actionText)
        {
            action = string.Empty;
            if (string.IsNullOrEmpty(actionText)) // null string
                return string.Empty;
            if (actionText.IndexOf('\n') > 0) // multiline
                return actionText;
            string[] t = actionText.Split(new string[] { ":{", ":=" }, StringSplitOptions.RemoveEmptyEntries);
            if (t.Length < 3) // unknown format
                return "//" + actionText;
            action = t[0];
            paramId = t[1];
            paramVal = t[2].TrimEnd('}');
            return action;
        }
        public string RemoveBrace(string param)
        {
             if (param.StartsWith("{"))
                param = param.Substring(1);
            if (param.EndsWith("}"))
                param = param.Remove(param.Length - 1);
            return param;
        }
    }

    public class ParserFactory : ActionParser
    {
        public new string ParseAction(string actionText)
        {
            string strText = PreProcess(actionText);
            if (string.IsNullOrEmpty(action))
                return strText;
            ActionParser p;
            switch (action.ToLower())
            {
                case "click":
                    p = new ClickParser();
                    break;
                case "keyup":
                    p = new KeyParser();
                    break;
                case "submit":
                    p = new FormParser();
                    break;
                case "documentcomplete":
                    p = new DocOKParser();
                    break;
                case "beforenavigate":
                    p = new NavParser();
                    break;
                case "newwindow":
                    p = new WinNewParser();
                    break;
                default:
                    p = new ActionParser();
                    break;
            }
            strText = p.ParseAction(actionText);
            return strText;
        }
    }

    class ClickParser : ActionParser
    {
        protected override string Parse()
        {
            string text = string.Format("p{{pageIndex}}.Click(\"{0}\"); //click:{1}", paramId, paramVal);
            return text;
        }
    }
    class KeyParser : ActionParser
    {
        protected override string Parse()
        {
            if (string.IsNullOrEmpty(paramVal))
                return "";
            string text = string.Format("p{{pageIndex}}.Fill(new string[]{{ \"{0}\", \"{1}\" }});//key:{1}", paramVal, paramId);
            return text;
        }
    }
    class FormParser : ActionParser
    {
        protected override string Parse()
        {
            string text = "";
            if (paramId == paramVal)
                text = "p{pageIndex}.Submit();";
            else
                text = string.Format("p{{pageIndex}}.Submit(\"{0}\");", paramId);
            return text;
        }
    }
    class NavParser : ActionParser
    {
        protected override string Parse()
        {
            string text = "";
            int i = paramVal.IndexOf("??");
            if (i < 1)
            {
                text = string.Format("GotoUrl(\"{0}\");", paramVal);
            }
            else
            {
                string data = paramVal.Substring(i + 2).Trim();
                string url = paramVal.Substring(0, i).Trim();
                text = string.Format("//PostToUrl(\"{0}\", \"{1}\")", url, data);
            }
            return text;
        }
    }
    class DocOKParser : ActionParser
    {
        protected override string Parse()
        {
            string url = paramVal;
            urlIndex++;
            string text = string.Format("var p{{pageIndex}} = WaitUrl(\"{0}\"); // DocumentComplete:{0}", url);
            return text;
        }
    }
    class WinNewParser : ActionParser
    {
        protected override string Parse()
        {
            string url = paramVal;
            string text = string.Format("//OpenWindow(\"{0}\");", url);
            return text;
        }
    }
    public class ActionFileParser
    {
        public string Parse(string file)
        {
            try
            {
                StreamReader sr = new StreamReader(file);
                StreamWriter sw = new StreamWriter(file + "_parsed.cs");
                ActionParser ap = new ParserFactory();
                while (!sr.EndOfStream)
                {
                    string scriptLine = "";
                    string line = sr.ReadLine();
                    scriptLine = ap.ParseAction(line);
                    if (string.IsNullOrEmpty(scriptLine))
                        continue;
                    sw.WriteLine(scriptLine);
                }
                sw.Flush();
                sw.Close();
                sr.Close();
            }
            catch (System.Exception ex)
            {

            }
            return "";
        }
    }


}